<?php
// +----------------------------------------------------------------------
// | Author: 发仔 <i@fazi.me> 
// +----------------------------------------------------------------------

namespace app\base\controller;

use think\Controller;
use think\Db;
use think\Cache;

class Base extends Controller
{
    //判断登录
	protected function isLogin() {
		
		$user_id = StrDecrypt(cookie('user_id'));
		if( $user_id ){
			$this->user = Db::name('user')->alias('u')->join('area a','u.area_id = a.area_id')->where('user_id',$user_id)->find();
		}
		$this->assign('user',$this->user);
	}
	
	public function _empty() {
		return $this->out(request()->action());
	}
	
	protected function out($action = '') {
		
		$action = $action ?: request()->action();
		$this->assign('JSFILE', '../template/'.request()->module().'/'.strtolower(request()->controller()).'/'.$action.'.js');
		$this->assign('action',$action);
		
		return $this->fetch($action);
		
	}
    
    /**
	* 自定义响应
	* @param undefined $success
	* @param undefined $url
	* 
	* @return
	*/
	protected function res($success,$msg = '',$url = '',$cache = '') {
		
		if($success){
			$error = 0;
			//清理缓存
			$cache && cache($cache,NULL);
		} else {
			$error = 1;
		}
		
		return $this->msg($url,$error,$msg);
	}
    
    /**
	* 操作结束后提示
	* @param str $url 
	* @param int $error 
	* @param str $msg
	* @param int $sec
	* 
	* @return
	*/
	public function msg($url = '', $error = 0, $msg = '',$sec = 2) {
		
		$data = [];
		//MSG 为数组时可带数据
		if(is_array( $msg )) {
			$data = $msg['data'];
			$msg = $msg['msg'][$error] ?: $msg[$error];
		}
		if(is_numeric($url)){
			$data['url'] = $url;
			$url = '';
		}

		$msg = $msg ? lang($msg) :'';#语言包
		
		if( request()->isAjax() ){
			
			if($error){
				return $this->error($msg,$url,$data,$sec);
			} else {
				return $this->success($msg,$url,$data,$sec);
			}
			
		} else {
			
			//直接跳转
			if($sec == 0) {
				return $this->redirect($url);
			}
			
//			$this->assign('JSFILE', '../application/index/view/common/msg.js');
//			
			$this->assign('url',$url);
			$this->assign('msg',$msg);
			$this->assign('sec',$sec);
			$this->assign('error',$error);
			return $this->fetch('common/msg');
			
		}
	}
}
